
from app.services.doubao.interface import UBALDOInterface
from app.services.doubao.model_registry import register_model


@register_model("image")
class ImageBasedUBALDO(UBALDOInterface):
    def recognize(self, file_path: str, full_text: str = "") -> dict:
        from app.services.tenant_config_service import get_tenant_config
        from openai import OpenAI
        import json
        from app.config import exConfig
        from app.services.doubao.utils import image_to_base64

        tenant_config = get_tenant_config().get_doubao_ai_config()
        b64 = image_to_base64(file_path)
        client = OpenAI(
            base_url="https://ark.cn-beijing.volces.com/api/v3",
            api_key=tenant_config.get('api_key', exConfig.DOUBAO_API_KEY),
        )

        try:
            response = client.chat.completions.create(
                model=tenant_config.get('model', exConfig.DOUBAO_MODEL_ID),
                messages=[{
                    "role": "user",
                    "content": [
                        {
                            "type": "image_url",
                            "image_url": {
                                "url": b64
                            }
                        },
                        {"type": "text",
                         "text":
                             """
                                        请将以下驾考题目解析为如下 JSON 格式，仅输出 JSON，不加任何说明或解释： answer 只输入答案序号 多个答案,分隔 答案序号和答案内容 一定要有 不能不给我生成，答案一定要准确 答案一定要准确 答案一定要准确。
                                        注意 
                                        [
                                           {{
                                        "type_text": "题目类型",
                                        "subject": "题目内容",
                                        "answer": "正确选项的序号（1 表示 A，2 表示 B，3 表示 C，4 表示 D）",
                                        "solve": "题目解析 简洁明了"
                                        "optionA": "选项A内容",
                                        "optionB": "选项B内容",
                                        "optionC": "选项C内容",
                                        "optionD": "选项D内容"
                                        }}
                                    ]
                                        """}
                    ]
                }],
                stream=False
            )

            response_text = response.choices[0].message.content
            parsed_result = json.loads(response_text)
            return parsed_result
        except Exception as e:
            print("❌ 图片识别失败：", e)
            return {}


# 注册策略
